// 导出页面为PDF格式
import html2Canvas from 'html2canvas';
import JsPDF from 'jspdf';
export default {
  install(Vue, options) {
    Vue.prototype.getPdf = function (pdfTitle,numTimes,examSHow) {
      if (!numTimes) {
        numTimes = 0
      }
      var that = this;
      that.loading = true;
      var title = pdfTitle;
      var pdfDom = document.getElementById('pdfDom');
      if (examSHow) {
        pdfDom.style.width= (pdfDom.offsetWidth/2)+'px';
      }
      var DomWidth = pdfDom.offsetWidth+1;
      var DomHeight = pdfDom.offsetHeight;
      var times = DomHeight / 592.28;
      var canvas = document.createElement("canvas");
      canvas.width = DomWidth;
      var num = Math.ceil(times / 92)
      if (times - numTimes * 92 > 92) {
        canvas.height = 592.28 * 92;
      } else {
        canvas.height = 592.28 * (times - numTimes * 92);
      }
      var context = canvas.getContext("2d");
      context.scale(1, 1);
      context.translate(0, -592.28 * numTimes * 92);
     
      html2Canvas(document.querySelector('#pdfDom'), {
        // allowTaint: true,
        useCORS: true, //看情况选用上面还是下面的，
        canvas: canvas,
        background: "#fff",
        // dpi: window.devicePixelRatio * 4, //将分辨率提高到特定的DPI 提高四倍
      }).then(function (canvas) {
        console.log(canvas);
        let contentWidth = canvas.width;
        let contentHeight = canvas.height;
        let pageHeight = (contentWidth / 592.28) * 841.89;
        let leftHeight = contentHeight;
        let position = 0;
        let imgWidth = 575.28;
        let imgHeight = (592.28 / contentWidth) * contentHeight;
        let pageData = canvas.toDataURL('image/jpeg', 1.0);
        let PDF = new JsPDF('', 'pt', 'a4');
        if (leftHeight < pageHeight) {
          PDF.addImage(pageData, 'JPEG', 10, 10, imgWidth, imgHeight);
        } else {
          while (leftHeight > 0) {
            PDF.addImage(pageData, 'JPEG', 10, position, imgWidth, imgHeight); //这里的10是左右边距
            leftHeight -= pageHeight;
            position -= 841.89;
            if (leftHeight > 0) {
              PDF.addPage();
            }
          }
        }
        PDF.save(title + '.pdf');
        if (numTimes+1 == num) {
          that.loading = false;
          that.pdfShow = false;
          if (examSHow) {
            pdfDom.style.width= (pdfDom.offsetWidth*2-1)+'px';
          }
        }else {
          that.getPdf(title,numTimes+1)
        }
        
      });
      
    };
  }
};






